package com.imooc.forkcgz;

import android.os.AsyncTask;
import android.widget.TextView;

import java.math.BigInteger;
import java.util.LinkedHashMap;

/**
 * Created by xyb on 2017/1/11.
 */

public class FibonAsyncTask extends AsyncTask<Integer, Integer, Integer> {

    private TextView textView;
    private LinkedHashMap<Integer, String> intBeen;
    //    private BigInteger bigInteger;
    private boolean isUp;
    private ListViewAdapter listViewAdapter;
    private CallBack callBack;


    public FibonAsyncTask( LinkedHashMap<Integer, String> intBeen, boolean isUp,CallBack callBack,ListViewAdapter listViewAdapter) {
        this.intBeen = intBeen;
        this.isUp = isUp;
        this.callBack = callBack;
        this.listViewAdapter = listViewAdapter;
    }



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Integer position) {
        super.onPostExecute(position);
        if (isCancelled()) {
            return;
        }
        callBack.onCallBack(position);
        if (listViewAdapter != null) {
            listViewAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected Integer doInBackground(Integer... params) {

        if (isCancelled()) {
            return 0;
        }
//        再次判断是否为空
        if (intBeen.get(params[0]) == null) {
            BigInteger fibonacci = FibonacciUtils.fibonacci(params[0] * params[0]);
            int res = fibonacci.compareTo(new BigInteger("10000000000"));
            if (res == 1) {
                String strBig = fibonacci.toString();
                int length = strBig.length();
                String first = strBig.substring(0, 1);
                String last = strBig.substring(1, 10);
                String s = first + "." + last + "E" + "+" + length;
                intBeen.put(params[0], s);
            } else {
                intBeen.put(params[0], fibonacci.toString());
            }

        }
        return params[0];
    }

    public interface CallBack {
        void onCallBack(Integer position);
    }
}
